//
//  CommissionViewController.m
//  Kfangchan
//
//  Created by liran on 14/11/5.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import "CommissionViewController.h"
#import "CommissionTableViewCell.h"
#import "AddBankViewController.h"

@interface CommissionViewController () {
    // 0:待结算 1:已结算
    int payType;
    UIView *emptyView;
    
    double sumNoPayCurrentMoney;
    double sumPayCurrentMoney;
    
    UISwipeGestureRecognizer *leftSwipeGestureRecognizer;
    UISwipeGestureRecognizer *rightSwipeGestureRecognizer;
}

@property (strong,nonatomic)  NSTimer *sumNoPayTimer;
@property (strong,nonatomic)  NSTimer *sumPayTimer;
@property (nonatomic) double sumNoPay;
@property (nonatomic) double sumPay;

@property (nonatomic) int cpage;
@property (strong, nonatomic) NSMutableArray *commissionArray;

@property (strong, nonatomic) IBOutlet UILabel *sumNoPayLabel;
@property (strong, nonatomic) IBOutlet UILabel *sumPayLabel;

@property (strong, nonatomic) IBOutlet UITableView *commissionTableView;

@property (strong, nonatomic) IBOutlet UIButton *sumNoPayButton;
@property (strong, nonatomic) IBOutlet UIButton *sumPayButton;

@property (strong, nonatomic) IBOutlet UIView *notBankView;

@end

@implementation CommissionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    sumNoPayCurrentMoney = 0.0;
    sumPayCurrentMoney = 0.0;
    
    payType = 0;
    self.sumNoPayButton.exclusiveTouch = YES;
    self.sumPayButton.exclusiveTouch = YES;
    
    // 定义手势左右滑动 用于切换待结 已结
    [self initSwipeGestureRecognizer];
    
    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"佣金管理"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"building_top_left.png"] Target:nil Selector:nil];
    
    __weak CommissionViewController *weak_self = self;
    //header
    [self.commissionTableView addHeaderWithCallback:^{
        [weak_self initList];
    } andIsChat:YES andIsOther:YES];
    //footer
    [self.commissionTableView addFooterWithCallback:^{
        weak_self.cpage++;
        [weak_self loadData];
    }];
    
    UIImageView *line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"partition.png"]];
    line.frame = CGRectMake(0, 50, 320, 0.5);
    [self.notBankView addSubview:line];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSString *bankNo = [AppConfig getAgent][AGENT_bankNo];
    float attachHeight = 0;
    if (bankNo == nil || bankNo.length == 0) {
        self.notBankView.hidden = NO;
        attachHeight = self.notBankView.size.height;
    } else {
        self.notBankView.hidden = YES;
    }
    self.commissionTableView.origin = CGPointMake(self.commissionTableView.origin.x, self.notBankView.origin.y + attachHeight);
    self.commissionTableView.size = CGSizeMake(self.commissionTableView.width, ScreenHeight - 110 - 35 - attachHeight);
    
    
    if (theApp.reloadCommissionList) {
        self.commissionArray = nil;
        theApp.reloadCommissionList = NO;
    }
    if (self.commissionArray == nil || self.commissionArray.count == 0) {
        [self changePay];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 列表相关
#pragma mark 初始化
- (void)initList {
    self.cpage = 1;
    if (self.commissionArray == nil) {
        self.commissionArray = [NSMutableArray array];
    }
    [self loadData];
}

#pragma mark 加载数据
- (void)loadData {
    __weak CommissionViewController *weak_self = self;
    NSDictionary *param = @{
                            @"cpage": [NSString stringWithFormat:@"%i", self.cpage],
                            @"status": [NSString stringWithFormat:@"%i", payType]};
    MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_COMMISSION_LIST completionHandler:^(id responseObject) {
        
        self.sumNoPay = [[responseObject valueForKey:@"sumNoPay"] doubleValue];
        self.sumPay = [[responseObject valueForKey:@"sumPay"] doubleValue];
        
        if (self.sumNoPayTimer && [self.sumNoPayTimer isValid]) {
            [self.sumNoPayTimer invalidate];
        }
        if (self.sumPayTimer && [self.sumPayTimer isValid]) {
            [self.sumPayTimer invalidate];
        }
        
        sumNoPayInterval = self.sumNoPay / 50;
        sumPayInterval = self.sumPay / 50;
        self.sumNoPayTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(repeatSumNoPay) userInfo:nil repeats:YES];
        self.sumPayTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(repeatSumPay) userInfo:nil repeats:YES];
        
        if (weak_self.cpage==1) {
            [weak_self.commissionArray removeAllObjects];
        }
        
        id totalPages = [responseObject objectForKey:@"totalPages"];
        if (weak_self.cpage >= [totalPages intValue]) {
            [weak_self.commissionTableView setFooterHidden:YES];
        } else {
            [weak_self.commissionTableView setFooterHidden:NO];
        }
        
        id list = [responseObject objectForKey:@"list"];
        if (![list isKindOfClass:[NSNull class]]) {
            CommissionList *commissionList = [[CommissionList alloc] initWithArray:list];
            [weak_self.commissionArray addObjectsFromArray:commissionList.array];
        }
        
        if (weak_self.commissionArray.count == 0) {
            [weak_self addEmptyView];
        } else {
            if (emptyView) {
                [emptyView removeFromSuperview];
            }
        }
        
        [weak_self.commissionTableView reloadData];
    } errorHandler:^(NSError *error) {
        showCustomAlertMessage(@"网路错误");
        [weak_self.commissionTableView headerEndRefreshing];
        [weak_self.commissionTableView setFooterHidden:YES];
    } finishHandler:^(id responseObject) {
        [weak_self.commissionTableView headerEndRefreshing];
        [weak_self.commissionTableView footerEndRefreshing];
    }];
    [self.opHandlers addObject:operation];
}

double sumNoPayInterval = MAXFLOAT;
double sumPayInterval = MAXFLOAT;
- (void)repeatSumNoPay {
    if (sumNoPayCurrentMoney < self.sumNoPay) {
        sumNoPayCurrentMoney += sumNoPayInterval;
        self.sumNoPayLabel.text = [NSString stringWithFormat:@"%.2f", sumNoPayCurrentMoney];
    } else {
        self.sumNoPayLabel.text = [NSString stringWithFormat:@"%.2f", self.sumNoPay];
        if ([self.sumNoPayTimer isValid]) {
            [self.sumNoPayTimer invalidate];
            sumNoPayCurrentMoney = 0;
        }
    }
}

- (void)repeatSumPay {
    if (sumPayCurrentMoney < self.sumPay) {
        sumPayCurrentMoney += sumPayInterval;
        self.sumPayLabel.text = [NSString stringWithFormat:@"%.2f", sumPayCurrentMoney];
    } else {
        self.sumPayLabel.text = [NSString stringWithFormat:@"%.2f", self.sumPay];
        if ([self.sumPayTimer isValid]) {
            [self.sumPayTimer invalidate];
            sumPayCurrentMoney = 0;
        }
    }
}

#pragma mark - UITableVIew
#pragma mark 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.commissionArray count];
}

#pragma mark 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"CommissionTableViewCell";
    
    Commission *entity = self.commissionArray[indexPath.row];
    
    CommissionTableViewCell *cell = (CommissionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        NSArray *cells = [[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil];
        cell = [cells objectAtIndex:0];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    [cell initCell:entity];
    return cell;
}

#pragma mark -
#pragma mark 手势滑动
- (void)initSwipeGestureRecognizer {
    leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(sumNoPay:)];
    rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(sumPay:)];
    leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    // 首次加载页面不需要
    //[self.view addGestureRecognizer:leftSwipeGestureRecognizer];
    [self.view addGestureRecognizer:rightSwipeGestureRecognizer];
}

#pragma mark -
#pragma mark 待结
- (IBAction)sumNoPay:(id)sender {
    payType = 0;
    [self changePay];
    [self.view removeGestureRecognizer:leftSwipeGestureRecognizer];
    if(![[self.view gestureRecognizers] containsObject:rightSwipeGestureRecognizer]) {
        [self.view addGestureRecognizer:rightSwipeGestureRecognizer];
    }
}

#pragma mark 已结
- (IBAction)sumPay:(id)sender {
    payType = 1;
    [self changePay];
    [self.view removeGestureRecognizer:rightSwipeGestureRecognizer];
    if(![[self.view gestureRecognizers] containsObject:leftSwipeGestureRecognizer]) {
        [self.view addGestureRecognizer:leftSwipeGestureRecognizer];
    }
}

- (void)changePay {
    self.sumNoPayButton.selected = !payType;
    self.sumNoPayButton.userInteractionEnabled = payType;
    self.sumPayButton.selected = payType;
    self.sumPayButton.userInteractionEnabled = !payType;
    [self initList];
}

#pragma mark -
#pragma mark 空结果页
- (void)addEmptyView {
    if(emptyView == nil) {
        emptyView = [[UIView alloc] initWithFrame:self.commissionTableView.bounds];
    }
    UIImageView *emptyImageView = (UIImageView *)[emptyView viewWithTag:9991208];
    if (!emptyImageView) {
        emptyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45, 320, 190)];
        emptyImageView.tag = 9991208;
    }
    if (payType == 0) {
        emptyImageView.image = [UIImage imageNamed:@"commission_empty_sumNoPay.png"];
    } else {
        emptyImageView.image = [UIImage imageNamed:@"commission_empty_sumPay.png"];
    }
    
    [emptyView addSubview:emptyImageView];
    [self.commissionTableView addSubview:emptyView];
}

#pragma mark -
#pragma mark 添加银行信息
- (IBAction)toBankInfo:(id)sender {
    AddBankViewController *avc = [[AddBankViewController alloc] init];
    avc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:avc animated:YES];
}

@end
